/**
 * Created by zhr on 2017/6/27.
 */
import React from "react";
import Relay from 'react-relay';
import { Table, message } from 'antd';
import { Button } from 'fly';
import Util from "../../../../../../util/Util";

//modal
import Reply from './components/reply';
import Send from './components/send';
import LogisticsDetails from './components/logisticsDetails';
import History from './components/history';
import ReplyDetail from './components/replyDetail';

import SampleExamineServerMutation from '../mutation/SampleExamineServerMutation';
export default class Tab extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            action:'goodsPlanList',//操作类型
            scId:12, //属于哪个打样单
            sampleId:3, //打样类型ID
            gspIds:null, //每一个商品的打样进度ID，'3,4,5'
            logisticsInfo:null, //物流信息
            examineUser:null, //审批人 1制衣厂、6贸易商、9品牌商
            result:null, //审批结果 0拒绝，1通过
            fileJSON:null,//审批报告
            explainDesc:null,//审批说明
            historyList: '',
            loading: true,
            goodsSamplePlanlList: null,
            approveType: null, //审批类型
            startProofing: false,
            user: null,
        }
        // this.start = this.start.bind(this);
        this.serviceType = sessionStorage.getItem('serviceType');
    }

    componentWillMount() {
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        if (this.props.scId && this.props.sampleId) {
            this.setState({
                scId: this.props.scId,
                sampleId: this.props.sampleId,
            },()=>{
                this.getSampleExamineServer('goodsPlanList','startAll');
            })
        } else {
            message.info('请按照规格进入此页面')
        }

    }
    getSampleExamineServer(action,startAll) {
        Relay.Store.commitUpdate(
            new SampleExamineServerMutation({
                action:action,
                scId:this.state.scId,
                sampleId:this.state.sampleId,
                gspIds:this.state.gspIds,
                logisticsInfo:this.state.logisticsInfo,
                examineUser:this.state.examineUser,
                result:this.state.result,
                fileJSON:JSON.stringify(this.state.fileJSON),
                explainDesc:this.state.explainDesc,
                approveType: this.state.approveType
            }),
            {
                onFailure: () => {
                    this.setState({
                        loading: false,
                    })
                    message.error('请求失败')
                },
                onSuccess: (response) => {
                    let errorCode = response.sampleExamineServer.responseData.errorCode;
                    if(errorCode=='0'){
                        let data = response.sampleExamineServer.responseData;
                        if (action == 'saveLogistics') {
                            message.success('保存物流信息成功')
                        } else if (action == 'start') {
                            message.success('开始打样成功')
                        } else if (action == 'examine') {
                            // message.success('批复成功');
                        } else if (action == 'restart') {
                            message.success('重新打样成功')
                        } else if (action == 'history') {
                            this.refs.history.setState({
                                historyVisible: true,
                                historyList: data.historyList,
                            })
                        }
                        this.setState({
                            partAName:data.partAName,
                            partBName:data.partBName,
                            goodsSamplePlanlList: data.goodsSamplePlanlList,
                            approveType: data.approveType,
                            loading: false,
                            historyList: data.historyList,
                        },()=>{
                            if (startAll == 'startAll') {
                                //startAll判断是否显示右上角开始打样按钮，首先map  如果gspIds == [] 表示都已经开始打样所以不显示右上角开始打样按钮
                                let gspIds = [];
                                this.state.goodsSamplePlanlList && this.state.goodsSamplePlanlList.map((v, i) => {
                                    v.status == 0 && v.off == 1 && gspIds.push(v.gspId)
                                });
                                gspIds.length ? (
                                    this.setState({
                                        startProofing: false,
                                    })
                                ) : (
                                    this.setState({
                                        startProofing: true,
                                    })
                                )
                            }
                        })
                    } else if(errorCode=='9999'){
                        message.error('参数错误')
                    }else {
                        this.setState({
                            loading: false,
                        })
                        message.error('请求失败')
                    }
                }
            }
        )
    }
    startAll() {
        ///表示开始打样所有款以逗号分割形式传值
        let gspIds = [];
        this.state.goodsSamplePlanlList && this.state.goodsSamplePlanlList.map((v,i)=>{
            v.status == 0 && v.off == 1 && gspIds.push(v.gspId)
        });
        gspIds.length ? (
            this.setState({
                gspIds: gspIds.join(','),
                startProofing: true
            },()=>{
                this.getSampleExamineServer('start')
            })
        ) : (
            this.setState({
                startProofing: false,
            })
        )

    }
    start(record, i,type) {
        //表示单个开始打样，点击单个开始打样也需要传startAll,时刻监听右上角开始打样按钮的显隐；
        this.setState({
            gspIds: JSON.stringify(record.gspId)
        },()=>{
            this.getSampleExamineServer(type,'startAll');
        })
    }
    //寄出 -> 物流信息的弹框,设置state gspIds
    send(record) {
        this.setState({
            gspIds: JSON.stringify(record.gspId)
        },()=>{
            this.refs.send.showModal()
        })

    }
    //寄出信息弹框OK回调里得到寄出信息，包括快递公司，编号，备注，字符串格式
    sendInfo(send) {
        //寄出输入框信息
        this.setState({
            logisticsInfo: send,
        },()=>{
            this.refs.send.setState({
                company:'',
                mark:'',
                num:''
            })
            this.getSampleExamineServer('saveLogistics');
        })
    }
    //寄出以后显示物流信息弹框
    showLogisticsDetails(record) {
        this.refs.logisticsDetails.setState({
            logisticsInfo: JSON.parse(record.logisticsInfo),
            logisticsDetailVisible: true,
        })
    }
    //批复弹框显示
    reply(record,Inx,b,user) { 
        if (user == 6 && this.state.approveType == 1){
            user = 1;   //制衣厂或者贸易商user都等于6   如果approveType == 1 ,那就是制衣厂（1）否则就是贸易商（6）
        }
        if (user == 6 && this.state.approveType == 2){
            user = 6;
        }
        this.setState({
            user,
            gspIds: JSON.stringify(record.gspId)
        },()=>{
            this.refs.reply.setState({
                replyVisible: true,
            },()=>{
                this.refs.reply.getToken()  //打卡弹框时获取上传图片所需要的token
            })
        })

    }
    //批复弹框点击确定之后获取输入信息
    replyInfo(result, fileJSON, explainDesc) {
        this.setState({
            examineUser: this.state.user, //1制衣厂、6贸易商、9品牌商
            result,
            fileJSON,
            explainDesc
        },()=>{
            this.refs.reply.setState({
                replyVisible: false,
                fileJson:[],
                selectValue: null,
                explainValue: '',
                defaultValue:'请选择批复结果'
            })
            this.getSampleExamineServer('examine');
            if (result == 0) {
                message.warn('请等待制衣厂重新打样')
                return;
            } else if (result == 1) {
                message.success('批复成功')
                return;
            }

        })
    }
    //重新打样
    restart(record) {
        this.setState({
            gspIds: JSON.stringify(record.gspId)
        },()=>{
            this.getSampleExamineServer('restart');
        })
    }
    //查看审批历史
    showHistory(record) {
        this.setState({
            gspIds: JSON.stringify(record.gspId)
        },()=>{
            this.getSampleExamineServer('history');
        })
    }
    //查看批复详情
    replyDetail(record, Inx) {
        this.refs.replyDetail.setState({
            replyDetailVisible: true,
            examineList: record.examineList,
            Inx:--Inx,
        })
    }
    //寄出的状态
    sendStatus(record,i) {
        if (record.status >= 2) {
            return (<span>
                        <span className="">已寄出</span>
                        <a className="step_show_detail" onClick={this.showLogisticsDetails.bind(this,record)}>物流详情</a>
                   </span>
            )
        } else if (record.status == 1 && (!this.props.isPartA) ) {
            return <Button className="step_btn" onClick={this.send.bind(this,record, i,'send')}>寄出</Button>
        }
    }
    progress(record, i) {
        let d = record && record ? record.startDate : null;  //开始打样时间
        let logisticsTime = record.logisticsInfo ? JSON.parse(record.logisticsInfo) : null;  //寄出（物流详情）时间
        let examine = record.examineList && record.examineList.length ? JSON.parse(record.examineList[0].examineDate) : null; //贸易商||制衣厂批复时间,类型是前两种1,2
        let examine1 = record.examineList && record.examineList.length && record.examineList.length == 2 ? JSON.parse(record.examineList[1].examineDate) : null;//品牌商批复 3
        const isPartA = this.props.isPartA;  //是否是甲方
        const partA = this.props.partA; // 甲方是否为0
        const orderClassify = this.props.orderClassify;  //1 表示录入成衣订单
        //乙方只显示开始打样、寄出按钮、重新打样按钮；
        //甲方显示批复按钮
        //如果是制衣厂寄出-》制衣厂批复情况，则制衣厂显示所有操作按钮；乙方录入成衣订单（为无甲方情况），会显示所有按钮，自己寄出自己批复；partA == 0 是无甲方情况
        //贸易商(serviceType == 6)并且是录入成衣订单（orderClassify == 1）  制衣厂操作所有

        return (
            <div className={this.state.approveType == 3 ? 'profing_step' : 'profing_step profing_step_30'}>
                <p>
                    {/*开始打样  css: profing_step_30 表示table只有三列的情况，占位33% 其他为四列  占位25%   profing_step_circle_start  已开始主色调背景   profing_step_circle_finished  已完成对勾形式  */}
                    <span style={{height:'25px'}}>{d ? Util.dateFormat(d) : ''}</span>
                    <span className={record.status == '0' ? 'profing_step_circle profing_step_circle_start' : 'profing_step_circle profing_step_circle_finished'}>
                        <b>{record.status == '0' ? null : '√'}</b>
                        <b></b>
                    </span>
                    {
                        !isPartA && record.status == 0　&& record.off ? (
                            <Button className='step_btn' onClick={this.start.bind(this,record, i,'start')}>开始打样</Button>
                        ) : null
                    }
                </p>
                <p>
                    {/*制衣厂寄出*/}
                    <span style={{height:'25px'}}>{logisticsTime ? Util.dateFormat(logisticsTime.date) : ''}</span>
                    {
                        record.status == 1 ? (
                            <span className='profing_step_circle profing_step_circle_start'>
                                <b></b>
                                <b></b>
                            </span>
                        ) : (
                            <span className={record.status >= 2 ? 'profing_step_circle profing_step_circle_finished' : 'profing_step_circle'}>
                                <b>√</b>
                                <b></b>
                            </span>
                        )
                    }
                    {
                        this.sendStatus(record,i)
                    }
                </p>
                {
                    <p>
                        {/*贸易商批复||制衣厂批复*/}
                        <span style={{height:'25px'}}>{examine ? Util.dateFormat(examine) : ''}</span>
                        {
                            record.status >= 2 && record.examineList.length ? (
                                record.examineList.length &&  record.examineList[0].result == 1 ? (
                                    <span className='profing_step_circle_finished'>
                                            <b>√</b>
                                            <b></b>
                                        </span>
                                ) : (
                                    <span className='profing_step_circle_refused'>
                                        <b>x</b>
                                        <b></b>
                                    </span>
                                )
                            ) : <span className={record.status == 2 ? 'profing_step_circle profing_step_circle_start' : 'profing_step_circle'}>
                                    <b></b>
                                    <b></b>
                                </span>
                        }

                        {
                            record.status >= 2 && record.examineList.length ? (
                                //状态为2表示制衣厂已寄出  可能的情况是贸易商和制衣厂
                                record.examineList.length && record.examineList[0].result == 1 ? (
                                    <span>
                                        <span>接受</span>
                                        <a className="step_show_detail" onClick={this.replyDetail.bind(this,record, '1')}>批复详情</a>
                                    </span>
                                ) : (
                                    <span>
                                        <span>不接受</span>
                                        <a className="step_show_detail" onClick={this.replyDetail.bind(this,record, '1')}>批复详情</a>
                                        {
                                            !isPartA ? (
                                                <Button className='step_btn' onClick={this.restart.bind(this,record, i,'restart')}>重新打样</Button>
                                            ) : null
                                        }
                                    </span>
                                )
                            ) : (
                                record.status >= 2 && !record.examineList.length && ((isPartA　&&　this.serviceType == 1) ||　!((this.serviceType == 6 && orderClassify == 1) || (this.serviceType == 1 && orderClassify != 1)))  ? (
                                //examineList没有长度表示制衣厂寄出，还未开始批复，而且只有甲方显示批复按钮|| 无甲方 自己寄出自己批复
                                <Button className='step_btn' onClick={this.reply.bind(this,record, i,'examine','6')}>批复</Button>
                                ) : null
                            )
                        }
                    </p>
                    // this.state.approveType == 1 ? (
                    //     <p>
                    //         {/*制衣厂批复*/}
                    //         <span>{d ? Util.dateFormat(d.date) : ''}</span>
                    //         {
                    //             record.status >= 2 && record.examineList.length ? (
                    //                 record.examineList.length &&  record.examineList[0].result == 1 ? (
                    //                     <span className='profing_step_circle_finished'>
                    //                         <b>√</b>
                    //                         <b></b>
                    //                     </span>
                    //                 ) : (
                    //                     <span className='profing_step_circle_refused'>
                    //                         <b>x</b>
                    //                         <b></b>
                    //                     </span>
                    //                 )
                    //             ) : <span className='profing_step_circle'>
                    //                     <b></b>
                    //                     <b></b>
                    //                 </span>
                    //         }
                    //
                    //         {
                    //             record.status >= 2 && record.examineList.length ? (
                    //                 record.examineList.length && record.examineList[0].result == 1 ? (
                    //                     <span>
                    //                         <span onClick={this.reply.bind(this,record, i,'examine')}>接受</span>
                    //                         <a className="step_show_detail" onClick={this.replyDetail.bind(this,record, '1')}>批复详情</a>
                    //                     </span>
                    //                 ) : (
                    //                     <span>
                    //                          <span onClick={this.reply.bind(this,record, i,'examine')}>不接受</span>
                    //                          <a className="step_show_detail" onClick={this.replyDetail.bind(this,record, '1')}>批复详情</a>
                    //                          <Button className='step_btn' onClick={this.restart.bind(this,record, i,'restart')}>重新打样</Button>
                    //                     </span>
                    //                 )
                    //             ) : (
                    //                 record.status >= 2 && !record.examineList.length &&　isPartA ? (
                    //                     <Button className='step_btn' onClick={this.reply.bind(this,record, i,'examine','1')}>批复</Button>
                    //                 ) : null
                    //
                    //             )
                    //         }
                    //     </p>
                    // ) : (
                    //
                    // )
                }
                {
                    this.state.approveType == 3 ? (
                        <p>
                            {/*品牌商批复*/}
                            <span style={{height:'25px'}}>{examine1 ? Util.dateFormat(examine1) : ''}</span>

                            {
                                record.status >= 4 &&　record.examineList.length == 1　&& record.examineList[0].result == 1 ? (
                                    <span className='profing_step_circle profing_step_circle_start'>
                                        <b></b>
                                        <b></b>
                                    </span>
                                ) : (
                                    record.status >= 5 && record.examineList.length ? (
                                        record.examineList[1].result == 0 ? (
                                            <span className='profing_step_circle_refused'>
                                            <b>x</b>
                                            <b></b>
                                        </span>
                                        ) : (
                                            <span className='profing_step_circle_finished'>
                                            <b>√</b>
                                            <b></b>
                                        </span>
                                        )
                                    ): (
                                        <span className='profing_step_circle'>
                                            <b></b>
                                            <b></b>
                                        </span>
                                    )
                                )
                            }
                            {
                                ((isPartA　&&　this.serviceType == 1) ||　!((this.serviceType == 6 && orderClassify == 1) || (this.serviceType == 1 && orderClassify != 1)))　&&　record.status == 4 &&　record.examineList.length == 1　&& record.examineList[0].result == 1 ? (
                                    <Button className='step_btn' onClick={this.reply.bind(this,record, i,'examine','9')}>批复</Button>
                                ) : null
                            }
                            {

                                record.status >= 5 && record.examineList.length && record.examineList[1].result == 0 ? (
                                    <span>
                                        <span>不接受</span>
                                        <a className="step_show_detail" onClick={this.replyDetail.bind(this,record, '2')}>批复详情</a>
                                        {
                                            !isPartA ? (
                                                <Button className='step_btn' onClick={this.restart.bind(this,record, i,'restart')}>重新打样</Button>
                                            ) : null
                                        }
                                    </span>
                                ) : null

                            }
                            {
                                record.status >= 5 && record.examineList.length && record.examineList[1].result == 1 ? (
                                    <span>
                                        <span>接受</span>
                                        <a className="step_show_detail" onClick={this.replyDetail.bind(this,record, '2')}>批复详情</a>
                                    </span>
                                ) : null
                            }

                        </p>
                    ): null
                }
            </div>
        )
    }
    back() {
        this.props.back()  //返回按钮
    }
    render() {
        const columns1 = [
            {
                title: '品名',
                dataIndex: 'productName',
                key: 'productName',
            },
            {
                title: '款号',
                dataIndex: 'styleNo',
                key: 'styleNo',
            },
            {
                title: '尺码',
                dataIndex: 'size',
                key: 'size',
                render:(text,record)=>{
                    return record.size && JSON.parse(record.size).join(',')
                }
            },
            {
                title: '打样',
                dataIndex: 'address',
                key: 'address',
                render:(text,record,i)=>{
                    const obj = {
                        children: '',
                        props: {},
                    };
                    obj.children = this.progress(record,i);
                    obj.props.colSpan = 3;
                    return obj;
                }
            },
            {
                title: '寄出',
                dataIndex: 'send',
                key: 'send',
                render:(text,r,i)=>{
                    const obj = {
                        children: '34',
                        props: {},
                    };

                    obj.props.colSpan = 0;
                    return obj;
                }
            },
            {
                title: '批复',
                dataIndex: 'a',
                key: 'a',
                render:(text,r,i)=>{
                    const obj = {
                        children: '34',
                        props: {},
                    };

                    obj.props.colSpan = 0;
                    return obj;
                }
            },
            {
                title: '批复历史',
                dataIndex: 'b',
                key: 'b',
                render:(text,record,i)=>{
                    return record.isReStart == 1 ? (
                        <a className="step_history" onClick={this.showHistory.bind(this,record)}>查看</a>
                    ) : null
                }
            }
        ];
        const columns2 = [
            {
                title: '品名',
                dataIndex: 'productName',
                key: 'productName',
            },
            {
                title: '款号',
                dataIndex: 'styleNo',
                key: 'styleNo',
            },
            {
                title: '尺码',
                dataIndex: 'size',
                key: 'size',
                render:(text,record)=>{
                    return record.size && JSON.parse(record.size).join(',')
                }
            },
            {
                title: '打样',
                dataIndex: 'address',
                key: 'address',
                render:(text,record,i)=>{
                    const obj = {
                        children: '',
                        props: {},
                    };
                    obj.children = this.progress(record,i);
                    obj.props.colSpan = 3;
                    return obj;
                }
            },
            {
                title: '寄出',
                dataIndex: 'send',
                key: 'send',
                render:(text,r,i)=>{
                    const obj = {
                        children: '34',
                        props: {},
                    };

                    obj.props.colSpan = 0;
                    return obj;
                }
            },
            {
                title: '批复',
                dataIndex: 'a',
                key: 'a',
                render:(text,r,i)=>{
                    const obj = {
                        children: '34',
                        props: {},
                    };

                    obj.props.colSpan = 0;
                    return obj;
                }
            },
            {
                title: '批复历史',
                dataIndex: 'b',
                key: 'b',
                render:(text,record,i)=>{
                    return record.isReStart == 1 ? (
                        <a className="step_history" onClick={this.showHistory.bind(this,record)}>查看</a>
                    ) : null
                }
            }
        ];
        const columns3 = [
            {
                title: '品名',
                dataIndex: 'productName',
                key: 'productName',
            },
            {
                title: '款号',
                dataIndex: 'styleNo',
                key: 'styleNo',
            },
            {
                title: '尺码',
                dataIndex: 'size',
                key: 'size',
                render:(text,record)=>{
                    return record.size && JSON.parse(record.size).join(',')
                }
            },
            {
                title: '打样',
                dataIndex: 'address',
                key: 'address',
                render:(text,record,i)=>{
                    const obj = {
                        children: '',
                        props: {},
                    };
                    obj.children = this.progress(record,i);
                    obj.props.colSpan = 4;
                    return obj;
                }
            },
            {
                title: '寄出',
                dataIndex: 'send',
                key: 'send',
                render:(text,r,i)=>{
                    const obj = {
                        children: '34',
                        props: {},
                    };

                    obj.props.colSpan = 0;
                    return obj;
                }
            },
            {
                title: '批复',
                dataIndex: 'a',
                key: 'a',
                render:(text,r,i)=>{
                    const obj = {
                        children: '34',
                        props: {},
                    };

                    obj.props.colSpan = 0;
                    return obj;
                }
            },
            {
                title: '品牌商批复',
                dataIndex: 'a',
                key: 'a',
                render:(text,r,i)=>{
                    const obj = {
                        children: '34',
                        props: {},
                    };

                    obj.props.colSpan = 0;
                    return obj;
                }
            },
            {
                title: '批复历史',
                dataIndex: 'b',
                key: 'b',
                render:(text,record,i)=>{
                    return record.isReStart == 1 ? (
                        <a className="step_history" onClick={this.showHistory.bind(this,record)}>查看</a>
                    ) : null
                }
            }
        ];
        let columns = [];
        if (this.state.approveType == 1) {
            columns = columns1
        } else if (this.state.approveType == 2){
            columns = columns2
        } else if (this.state.approveType == 3){
            columns = columns3
        }
        return (
            <div className="cp_header_tab">
                <p>
                    <span onClick={this.back.bind(this)} className="cp_header_tab_back"></span>
                    <span className="cp_header_type">{this.props.name}</span>
                    <span>计划交期：{Util.dateFormat(this.props.deliveryDate)}</span>
                    <span className="cp_header_tab_step">
                        <a>{this.state.partBName}寄出</a>
                        <a>{this.state.partAName}批复</a>
                        {
                            this.state.approveType == 3 ? <a>品牌商批复</a> : null
                        }
                    </span>
                    {
                        this.props.isPartA || this.state.startProofing ?
                            null :
                            <span className="start_profing_style" style={{float:'right'}}><Button onClick={this.startAll.bind(this)}>开始打样</Button></span>
                    }
                </p>
                <br style={{clear:'both'}}/>
                <Table
                    dataSource={this.state.goodsSamplePlanlList}
                    columns={columns}
                    className={this.props.name == '尺码样' ?'order_table proofing_step_table_pagination' : 'order_table proofing_step_table_pagination proofing_step_table'}
                    bordered
                    pagination={false}
                    loading={this.state.loading}
                />
                <Reply ref={'reply'} replyInfo={this.replyInfo.bind(this)}/>
                <ReplyDetail ref={'replyDetail'} />
                <Send ref={'send'} sendInfo={this.sendInfo.bind(this)}/>
                <LogisticsDetails ref={'logisticsDetails'} />
                <History ref={'history'} />
            </div>
        )

    }
}